<template lang="">
  <div class="cart">
    <div class="head">
      <div>30天无忧退货</div>
      <div>48小时快速退款</div>
      <div>满88元免邮费</div>
    </div>
    <div class="list">
        <van-swipe-cell v-for="item in cartList" :key="item.id" class="item">
           <div class="item-content">
             <van-checkbox class="check" v-model="item.isChecked"></van-checkbox>
           <img :src="item.list_pic_url"/>
            <div class="info">
              <p>{{item.goods_name}}</p>
              <p>￥{{item.retail_price}}</p>
            </div>
            <span class='num'>x {{item.number}}</span>
           </div>
            <template #right>
              <van-button square text="删除" type="danger" class="delete-button" @click="deleteItem(item)"/>
          </template>
        </van-swipe-cell>
    </div>
    <div class="footer">
      <div class="left">
         <van-checkbox v-model="ischeckedAll">全选</van-checkbox>
      </div>
      <div class="right">
        <span class="total">￥{{total}}</span>
        <span class="placeorder" @click="placeorder">下单</span>
      </div>
    </div>
  </div>
</template>
<script>
import { cartList, submitAction, deleteAction } from "@/api/cart/index";
export default {
  data() {
    return {
      cartList: [],
    };
  },

  methods:{
    getCartList(){
      cartList({
            openId: localStorage.getItem("openId"),
          }).then((res) => {
            
            let list = res.data.data;
            console.log(list);
            this.cartList = list.map((item)=>{
              return {
                ...item,
                isChecked: false
              }
            });
          });
    },
    //删除商品
    deleteItem(item){
      deleteAction({
        id: item.id,
      }).then(res=>{
        this.$toast("删除成功");
        this.getCartList();
      });
    },
    // 下单
    placeorder(){
      if(this.total <= 0) {
         this.$toast("请选择商品");
        return;
      }
      submitAction({
        allPrise: this.total,
        goodsId: this.cartList.filter(item=>item.isChecked).map(item=> item.goods_id).join(),
        openId: localStorage.getItem("openId")
      }).then((res)=>{
        console.log(res);
        if (res.data.data) {
          this.$router.push('/cart/orderconfirm');
        }
      });
    }
  },

  computed:{
    // 统计被选中的商品
    total(){
      return this.cartList.reduce((sum, item)=>{
        if (item.isChecked) {
          return sum+=item.retail_price * item.number;
        } else {
          return sum;
        }
      },0)
    },
    // 全选
    ischeckedAll:{
      get(){
        return this.cartList.every((item)=>item.isChecked);
      },
      set(val){
        this.cartList.forEach((item)=>{
          item.isChecked = val;
        })
      }
    }
  },

  created() {
    this.getCartList();
  },
};
</script>
<style lang="scss" scoped>
@import "./index.scss";
</style>
